package com.weike.client.controller;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
//import lombok.extern.slf4j.Slf4j;
import groovy.util.logging.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import reactor.core.publisher.Flux;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


@RestController
@RequestMapping("deepSeek")
@Slf4j
public class OpenAIController {

    private static final Logger log = LoggerFactory.getLogger(OpenAIController.class);
    @Value("${ai.config.deepseek.apiKey}")
    private String API_KEY;

    @Value("${ai.config.deepseek.baseUrl}")
    private String API_URL;

    @Value("${ai.config.role}")
    private String ROLE;

    @Autowired
    private ChatClient chatClient;

    // 用于保存每个用户的对话历史
    private final Map<String, List<Map<String, String>>> sessionHistory = new ConcurrentHashMap<>();

    private final ExecutorService executorService = Executors.newCachedThreadPool();
    private final ObjectMapper objectMapper = new ObjectMapper();
    @GetMapping()
    public ModelAndView chat(ModelAndView modelAndView) {
        modelAndView.setViewName("chat");
        System.out.println(12322);
        return modelAndView;
    }


    @PostMapping(value = "/chat", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public SseEmitter chat(@RequestBody String question) {
        SseEmitter emitter = new SseEmitter(-1L);

//        String question = "你好，老八叫什么";

        // 获取流式回答
/*        Flux<String> responseFlux = chatClient.prompt(question)
                .stream().content().any(item)
                .map(response -> response.getResult().getOutput().getContent()); */

        Flux<String> responseFlux = chatClient.prompt(question)
                .stream().content();

        // 订阅 Flux 并发送数据
        responseFlux.subscribe(
                content -> {
                    try {
                        System.err.println(content);
                        emitter.send(SseEmitter.event().data(content));
                    } catch (IOException e) {
                        emitter.completeWithError(e);
                    }
                },
                error -> emitter.completeWithError(error),
                () -> emitter.complete()
        );

        return emitter;
    }
}